package com.freewater.cargotracker.domain.model.cargo;

import com.freewater.cargotracker.domain.common.Value;
import com.freewater.cargotracker.domain.model.customer.Customer;
import com.freewater.cargotracker.domain.model.customer.Role;
import org.apache.commons.lang3.Validate;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CargoCustomers implements Serializable, Value {

    private static final long serialVersionUID = 1L;

    public static final CargoCustomers EMPTY_CUSTOMERS = new CargoCustomers();

    private Map<Role, Customer> customers = new HashMap<>();

    public CargoCustomers() {

    }

    public CargoCustomers(Map<Role, Customer> customers) {
        this.addCustomers(customers);
    }

    public CargoCustomers(CargoCustomers cargoCustomers) {
        this.customers = new HashMap<>(cargoCustomers.getCustomers());
    }

    public Map<Role, Customer> getCustomers() {
        return Collections.unmodifiableMap(customers);
    }

    /**
     * 批量添加Customer
     *
     * @param customerMap
     */
    private void addCustomers(Map<Role, Customer> customerMap) {
        Validate.notNull(customerMap, "Customers are required");
        customerMap.forEach((role, customer) -> this.addCustomer(customer, role));
    }

    /**
     * 添加Customer
     *
     * @param customer
     * @param role
     */
    private void addCustomer(Customer customer, Role role) {
        Validate.notNull(customer, "Customer is required");
        Validate.notNull(role, "Role is required");

        final boolean existCustomer = this.customers.containsKey(role);
        if (existCustomer) {
            throw new RuntimeException("Customer with role already exist");
        }
        this.customers.put(role, customer);
    }
}
